import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Demo5 {
    //创建简易的线程池
    static class MyThreadPool {
        //创建一个阻塞队列
        private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
        public MyThreadPool(int n) {
            for (int i = 0; i < 5; i++) {
                Thread t1 = new Thread(() -> {
                    while (true) {
                        try {
                            Runnable task = queue.take();
                            //在当前线程中执行该任务
                            task.run();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                },"Thread" + i);
                t1.start();
            }
        }
        public void submit(Runnable task) throws InterruptedException {
            queue.put(task);
        }
    }
    //往线程池中添加任务
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(5);
        for (int i = 0; i < 5000; i++) {
            int id = i;
            pool.submit(()->{
                Thread cur = Thread.currentThread();
                System.out.println(cur.getName() +" " + id);
            });
        }
        Thread.sleep(1000);
    }
}
